﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragKey : MonoBehaviour
{
    //public static DragKey Instance;
    public bool canMove = true;
    public AudioClip Fall;

    private float moveSpeed = 0.2f;

    bool isTouching = false;
    private GameObject curObj;
    private bool canPlay = false;
    private AudioSource audios;

    private void Start()
    {
        //Instance = this;
        audios = GameObject.Find("Main Camera").GetComponent<AudioSource>();
    }

    IEnumerator OnMouseDown()
    {
        canPlay = true;

        //将物体由世界坐标系转化为屏幕坐标系，由vector3 结构体变量ScreenSpace存储，以用来明确屏幕坐标系Z轴的位置
        Vector3 ScreenSpace = Camera.main.WorldToScreenPoint(transform.position);

        //完成了两个步骤，1由于鼠标的坐标系是2维的，需要转化成3维的世界坐标系，2只有三维的情况下才能来计算鼠标位置与物体的距离，offset即是距离
        Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z));

        //当鼠标左键按下时
        while (Input.GetMouseButton(0) && canMove==true)
        //while((Input.touches[0].phase==TouchPhase.Moved || Input.touches[0].phase==TouchPhase.Stationary) && Input.touchCount > 0 && canMove==true)
        {
            gameObject.transform.localEulerAngles = new Vector3(0,0,0);

            //得到现在鼠标的2维坐标系位置
            Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z);
            //Vector3 curScreenSpace = new Vector3(Input.touches[0].deltaPosition.x, Input.touches[0].deltaPosition.y, ScreenSpace.z);


            //将当前鼠标的2维位置转化成三维的位置，再加上鼠标的移动量
            Vector3 CurPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;

            //CurPosition就是物体应该的移动向量赋给transform的position属性
            transform.position = CurPosition;

            //等待直到下一个固定帧速率更新函数
            yield return new WaitForFixedUpdate();

        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name=="Plane02" && canPlay==true)
        {
            Debug.Log("撞击地面");
            audios.clip = Fall;
            audios.Play();
            audios.loop = false;
            canPlay = false;
            //可重新拖动
            canMove = true;
        }
        else if (collision.gameObject.name=="Collider1" || collision.gameObject.name == "Collider2")
        {
            canMove = false;
            StartCoroutine("WaitMove");
        }
    }
    //可重新拖动
    IEnumerator WaitMove()
    {
        yield return new WaitForSeconds(0.5f);
        canMove = true;
    }

}
